#!/bin/bash

# 检查是否提供了两个参数
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 input.mp4 output.ts"
    exit 1
fi

# 获取输入和输出文件名
input_file="$1"
output_file="$2"

# 期望的视频编码
expected_codec="h264"

# 使用ffprobe获取视频编码
actual_codec=$(ffprobe -v error -select_streams v:0 -show_entries stream=codec_name -of default=noprint_wrappers=1:nokey=1 "$input_file")

# 使用ffprobe获取rotate元数据
rotate_metadata=$(ffprobe -v error -select_streams v:0 -show_entries stream_tags=rotate -of default=noprint_wrappers=1:nokey=1 "$input_file")

# 检查视频编码
if [ "$actual_codec" = "$expected_codec" ]; then
    echo "The video is encoded with H.264."
    
    # 根据rotate元数据旋转视频
    if [ -n "$rotate_metadata" ]; then
               
        # 如果需要旋转，则重新编码视频
        ffmpeg -y -loglevel verbose -i "$input_file" -c:v libx264 -preset veryfast -crf 23 -c:a copy -vbsf h264_mp4toannexb "$output_file"
    else
        # 如果不需要旋转，直接复制视频和音频流
        ffmpeg -y -loglevel verbose -i "$input_file" -vcodec copy -acodec copy -vbsf h264_mp4toannexb "$output_file"
    fi
    
else
    echo "The video is NOT encoded with H.264. It is encoded with $actual_codec."
   
    ffmpeg -y -loglevel verbose -i "$input_file" -c:v libx264 -preset veryfast -crf 23 -c:a aac -b:a 128k -f mpegts "$output_file"
fi

# 检查ffmpeg执行结果
if [ $? -eq 0 ]; then
    echo "Video conversion successful."
else
    echo "Video conversion failed. Check the logs for more information."
fi